document.addEventListener('DOMContentLoaded', () => {
    // DOM Elements
    const apiKeyInput = document.getElementById('api-key');
    const modelSelect = document.getElementById('model-select');
    const imageUpload = document.getElementById('image-upload');
    const imagePreviewContainer = document.getElementById('image-preview-container');
    const imagePreview = document.getElementById('image-preview');
    const uploadPlaceholder = document.getElementById('upload-placeholder');
    const promptInput = document.getElementById('prompt-input');
    const generateBtn = document.getElementById('generate-btn');
    const resultContainer = document.getElementById('result-container');
    const resultImageWrapper = document.getElementById('result-image-wrapper');
    const resultImage = document.getElementById('result-image');
    const resultUrlInput = document.getElementById('result-url');
    const copyUrlBtn = document.getElementById('copy-url-btn');
    const spinner = document.getElementById('spinner');
    const statusMessage = document.getElementById('status-message');
    const errorMessage = document.getElementById('error-message');
    const promptModulesContainer = document.getElementById('prompt-modules');
    const aspectRatioContainer = document.getElementById('aspect-ratio-selector');
    const resolutionContainer = document.getElementById('resolution-selector');
    const numberContainer = document.getElementById('number-selector');

    let selectedFile = null;

    // -- Data --
    const promptModules = [
        { name: "3D模型", value: "turn this photo into a character figure. Behind it, place a box with the character’s image printed on it, and a computer showing the Blender modeling process on its screen. In front of the box, add a round plastic base with the character figure standing on it. set the scene indoors if possible." },
        { name: "素描转照片", value: "Transform sketch into realistic photo with natural lighting and photographic details." },
        { name: "产品海报", value: "Transform photo into product poster style. Clean commercial advertising look with bold graphics and promotional layout." },
        { name: "图像放大", value: "Upscale image resolution while maintaining quality and detail clarity." },
        { name: "姿势编辑", value: "Create a pose sheet for this character. Show multiple poses including standing, walking, sitting, jumping, and various gestures." },
        { name: "服装更换", value: "Replace character's clothing with target outfit from reference image. Maintain original pose, facial expression, background and realism. Ensure new clothing fits naturally with consistent lighting and shadows. Change only clothes, not identity or environment." }
    ];
    const aspectRatios = ["Auto", "16:9", "9:16", "4:3", "3:4", "1:1"];
    const resolutions = ["1K", "2K", "4K"];
    const numbers = [1, 2, 3, 4];

    // -- UI Initialization --
    function createSelectorButtons(container, items, activeDefault) {
        container.innerHTML = '';
        items.forEach(item => {
            const button = document.createElement('button');
            button.textContent = item;
            button.dataset.value = item;
            if (item === activeDefault) {
                button.classList.add('active');
            }
            container.appendChild(button);
        });
    }

    function initUI() {
        promptModules.forEach(p => {
            const button = document.createElement('button');
            button.textContent = p.name;
            button.addEventListener('click', () => promptInput.value = p.value);
            promptModulesContainer.appendChild(button);
        });
        createSelectorButtons(aspectRatioContainer, aspectRatios, "Auto");
        createSelectorButtons(resolutionContainer, resolutions, "1K");
        createSelectorButtons(numberContainer, numbers, 1);
    }

    // -- Event Listeners --
    apiKeyInput.addEventListener('change', loadModels);
    
    imagePreviewContainer.addEventListener('click', () => imageUpload.click());
    imagePreviewContainer.addEventListener('dragover', e => e.preventDefault());
    imagePreviewContainer.addEventListener('drop', e => { e.preventDefault(); handleFile(e.dataTransfer.files[0]); });
    imageUpload.addEventListener('change', e => handleFile(e.target.files[0]));

    document.querySelectorAll('.param-selector').forEach(container => {
        container.addEventListener('click', e => {
            if (e.target.tagName === 'BUTTON') {
                container.querySelector('.active')?.classList.remove('active');
                e.target.classList.add('active');
            }
        });
    });

    generateBtn.addEventListener('click', handleGenerate);
    copyUrlBtn.addEventListener('click', copyUrlToClipboard);

    // -- Core Functions --
    async function loadModels() {
        const apiKey = apiKeyInput.value.trim();
        if (!apiKey) { showError("请先输入 API Master Key。"); return; }
        hideError();
        
        try {
            const response = await fetch('/v1/models', { headers: { 'Authorization': `Bearer ${apiKey}` } });
            if (!response.ok) throw new Error((await response.json()).detail || '加载模型失败');
            
            const data = await response.json();
            modelSelect.innerHTML = '';
            data.data.forEach(model => {
                const option = document.createElement('option');
                option.value = model.id;
                option.textContent = model.id;
                modelSelect.appendChild(option);
            });
        } catch (error) {
            showError(`加载模型列表失败: ${error.message}`);
        }
    }

    function handleFile(file) {
        if (!file) return;
        selectedFile = file;
        const reader = new FileReader();
        reader.onload = e => {
            imagePreview.src = e.target.result;
            imagePreview.classList.remove('hidden');
            uploadPlaceholder.classList.add('hidden');
        };
        reader.readAsDataURL(file);
    }

    async function handleGenerate() {
        const apiKey = apiKeyInput.value.trim();
        const model = modelSelect.value;
        const prompt = promptInput.value.trim();

        if (!apiKey || !model || !prompt || !selectedFile) {
            showError("请确保 API Key、模型、图片和 Prompt 指令都已填写/上传。");
            return;
        }

        setLoading(true);

        const formData = new FormData();
        formData.append('image', selectedFile);
        formData.append('prompt', prompt);
        formData.append('model', model);
        formData.append('aspect_ratio', document.querySelector('#aspect-ratio-selector .active').dataset.value);
        formData.append('size', document.querySelector('#resolution-selector .active').dataset.value);
        formData.append('n', document.querySelector('#number-selector .active').dataset.value);

        try {
            const response = await fetch('/v1/images/edits', {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${apiKey}` },
                body: formData
            });

            const result = await response.json();
            if (!response.ok) throw new Error(result.detail || '生成失败，未知错误。');

            if (result.data && result.data.length > 0 && result.data[0].url) {
                const imageUrl = result.data[0].url;
                resultImage.src = imageUrl;
                resultUrlInput.value = imageUrl;
                resultImageWrapper.classList.remove('hidden');
                statusMessage.classList.add('hidden');
            } else {
                throw new Error('API 返回了成功状态，但没有图片 URL。');
            }
        } catch (error) {
            showError(error.message);
        } finally {
            setLoading(false);
        }
    }

    function copyUrlToClipboard() {
        resultUrlInput.select();
        document.execCommand('copy');
        copyUrlBtn.textContent = '已复制!';
        setTimeout(() => { copyUrlBtn.textContent = '复制'; }, 2000);
    }

    // -- UI State Helpers --
    function setLoading(isLoading) {
        generateBtn.disabled = isLoading;
        spinner.classList.toggle('hidden', !isLoading);
        if (isLoading) {
            statusMessage.textContent = '正在生成中，这可能需要几分钟，请耐心等待...';
            statusMessage.classList.remove('hidden');
            resultImageWrapper.classList.add('hidden');
            hideError();
        }
    }

    function showError(message) {
        errorMessage.textContent = message;
        errorMessage.classList.remove('hidden');
        statusMessage.classList.add('hidden');
        resultImageWrapper.classList.add('hidden');
    }

    function hideError() {
        errorMessage.classList.add('hidden');
    }

    // -- Initial Load --
    initUI();
    loadModels();
});
